<template>
  <div class="project-form">
    <el-form ref="projectRef" :model="whitePaperProject" class="form-container" :rules="projectRules" label-width="0px">
      <div class="form-row">
        <div class="form-item" style="width: 280px;">
          <span class="label-wrap required">
            <span class="required-mark">*</span>
            <span class="label-text">企业/机构名称</span>
          </span>
          <el-form-item prop="orgName" class="el-form-item__custom">
            <el-input v-model="whitePaperProject.orgName" placeholder="请输入企业或机构名称" class="form-input" :border="false"
              maxlength="50" />
          </el-form-item>
        </div>
        <div class="form-item" style="width: 280px;">
          <span class="label-wrap required">
            <span class="required-mark">*</span>
            <span class="label-text">所在行业</span>
          </span>
          <el-form-item prop="industry" class="el-form-item__custom">
            <el-input v-model="whitePaperProject.industry" placeholder="请输入所在行业" class="form-input" :border="false"
              maxlength="30" />
          </el-form-item>
        </div>
      </div>

      <div class="form-row">
        <div class="form-item full-width">
          <span class="label-wrap required">
            <span class="required-mark">*</span>
            <span class="label-text">联系地址</span>
          </span>
          <el-form-item prop="address" class="el-form-item__custom">
            <el-input v-model="whitePaperProject.address" placeholder="请输入联系地址" class="form-input" :border="false"
              maxlength="100" />
          </el-form-item>
        </div>
      </div>

      <div class="form-row">
        <div class="form-item" style="width: 280px;">
          <span class="label-wrap required">
            <span class="required-mark">*</span>
            <span class="label-text">联系邮箱</span>
          </span>
          <el-form-item prop="email" class="el-form-item__custom">
            <el-input v-model="whitePaperProject.email" placeholder="请输入联系邮箱" class="form-input" :border="false"
              maxlength="50" />
          </el-form-item>
        </div>
        <div class="form-item" style="width: 280px;">
          <span class="label-wrap">
            <span class="label-text">企业/机构官网</span>
          </span>
          <el-form-item class="el-form-item__custom">
            <el-input v-model="whitePaperProject.officialWebsite" placeholder="请输入企业或机构官网链接" class="form-input"
              :border="false" maxlength="200" />
          </el-form-item>
        </div>
      </div>

      <div class="form-row">
        <div class="form-item">
          <span class="label-wrap">
            <span class="label-text">企业/机构微信公众号</span>
          </span>
          <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="uploadHeaders"
            :on-preview="handlePreview">
            <div class="upload-placeholder" v-if="!getFullUrl(whitePaperProject.officialAccountImgUrl)">
              <i class="el-icon-plus"></i>
            </div>
            <img v-if="whitePaperProject.officialAccountImgUrl"
              :src="getFullUrl(whitePaperProject.officialAccountImgUrl)" class="avatar">
          </el-upload>
        </div>
      </div>

      <div class="form-row">
        <div class="form-item full-width">
          <span class="label-wrap">
            <span class="label-text">企业/机构简介</span>
          </span>
          <el-form-item class="el-form-item__custom">
            <el-input type="textarea" v-model="whitePaperProject.briefIntroduction" placeholder="请输入企业或机构简介"
              class="form-textarea" :border="false" rows="3" maxlength="500" />
          </el-form-item>
        </div>
      </div>

      <div class="form-row">
        <div class="form-item">
          <span class="label-wrap">
            <span class="label-text">相关资料附件</span>
          </span>
          <el-upload class="file-upload" :action="uploadUrl" :on-preview="handleFilePreview" :on-remove="handleRemove"
            :before-remove="beforeRemove" multiple :limit="3" :file-list="showFileList" :on-exceed="handleExceed"
            :on-success="handleFileSuccess" :auto-upload="false" :headers="uploadHeaders">
            <el-button size="small" type="primary">上传</el-button>
          </el-upload>
        </div>
      </div>
    </el-form>

    <el-dialog v-model="previewVisible" :close-on-click-modal="true" :close-on-press-escape="true" width="600px"
      title="图片预览">
      <img :src="previewImageUrl" alt="预览图片" style="width: 100%; height: auto; object-fit: contain;">
    </el-dialog>

    <el-dialog v-model="filePreviewVisible" title="附件预览" width="300px">
      <div class="file-preview-content">
        <p>文件名称：{{ previewFileName }}</p>
        <el-button type="text" @click="downloadFile">点击下载文件</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getProject } from '@/api/whitepaper/myproject'

export default {
  name: "ProjectInfo",
  props: {
    formData: { type: Object, default: () => ({}) },
    whitePaperName: { type: String, default: "" },
    projectId: { type: Number, default: 0 }
  },
  data() {
    return {
      whitePaperProject: {
        orgName: "",
        industry: "",
        address: "",
        email: "",
        officialWebsite: "",
        officialAccountImgUrl: "",
        briefIntroduction: "",
      },
      baseApi: process.env.VUE_APP_BASE_API,
      uploadUrl: `${process.env.VUE_APP_BASE_API}/system/oss/file/upload`,
      uploadHeaders: {
        Authorization: `Bearer ${getToken()}`
      },
      showFileList: [],
      fileList: [],
      projectRules: {
        orgName: [
          { required: true, message: "请输入企业/机构名称", trigger: ["blur", "change"] },
          { max: 50, message: "名称长度不超过50个字符", trigger: ["blur", "change"] }
        ],
        industry: [
          { required: true, message: "请输入所在行业", trigger: ["blur", "change"] },
          { max: 30, message: "行业长度不超过30个字符", trigger: ["blur", "change"] }
        ],
        address: [
          { required: true, message: "请输入联系地址", trigger: ["blur", "change"] },
          { max: 100, message: "地址长度不超过100个字符", trigger: ["blur", "change"] }
        ],
        email: [
          { required: true, message: "请输入联系邮箱", trigger: ["blur", "change"] },
          { type: "email", message: "请输入正确的邮箱格式", trigger: ["blur", "change"] },
          { max: 50, message: "邮箱长度不超过50个字符", trigger: ["blur", "change"] }
        ],
      },
      previewVisible: false,
      previewImageUrl: "",
      filePreviewVisible: false,
      previewFileName: "",
      previewFileUrl: ""
    };
  },
  watch: {
    whitePaperProject: {
      deep: true,
      handler(val) {
        this.$emit("updateForm", {
          whitePaperProject: val,
          fileList: this.fileList
        });
      },
    },
    projectId: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.getProjectDetail(newVal)
        }
      }
    },
    "$store.getters.token": {
      handler() {
        this.uploadHeaders.Authorization = `Bearer ${getToken()}`;
      }
    }
  },
  methods: {
    validate(callback) {
      this.$refs.projectRef.validate(callback);
    },
    resetForm() {
      this.$refs.projectRef?.resetFields();
      this.whitePaperProject.officialAccountImgUrl = "";
      this.showFileList = [];
      this.fileList = [];
      this.previewVisible = false;
      this.filePreviewVisible = false;
    },
    getFullUrl(url) {
      if (!url) return "";
      return url.startsWith('http') || url.startsWith(this.baseApi) ? url : `${this.baseApi}${url}`;
    },
    getRelativeUrl(fullUrl) {
      if (!fullUrl) return "";
      return fullUrl.startsWith(this.baseApi) ? fullUrl.replace(this.baseApi, "") : fullUrl;
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 200 && res.data?.fileUrl) {
        this.whitePaperProject.officialAccountImgUrl = this.getRelativeUrl(res.data.fileUrl);
        this.previewImageUrl = res.data.fileUrl;
        this.previewVisible = true;
      } else {
        this.$message.error("公众号图片上传失败");
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) this.$message.error("仅支持图片格式");
      if (!isLt2M) this.$message.error("图片不超过2MB");
      return isImage && isLt2M;
    },
    handleFileSuccess(response, file, fileList) {
      if (response.code === 200 && response.data?.fileUrl) {
        const relativeUrl = this.getRelativeUrl(response.data.fileUrl);
        this.fileList.push({
          fileName: file.name,
          originFileName: file.name,
          fileUrl: relativeUrl,
          delFlag: "0"
        });
        this.showFileList = fileList.map(item => ({
          name: item.name,
          url: this.getFullUrl(item.url || item.response?.data?.fileUrl)
        }));
      } else {
        this.$message.error("附件上传失败");
      }
    },
    handleRemove(file, fileList) {
      this.showFileList = fileList;
      const fileUrl = this.getRelativeUrl(file.url);
      this.fileList = this.fileList.filter((item) => item.fileUrl !== fileUrl);
    },
    handlePreview(file) {
      if (file.response) {
        this.previewImageUrl = file.response.data.fileUrl;
      } else if (file.raw) {
        this.previewImageUrl = URL.createObjectURL(file.raw);
      } else if (this.whitePaperProject.officialAccountImgUrl) {
        this.previewImageUrl = this.getFullUrl(this.whitePaperProject.officialAccountImgUrl);
      }
      this.previewVisible = true;
    },
    handleFilePreview(file) {
      this.previewFileName = file.name;
      this.previewFileUrl = this.getFullUrl(file.url);
      this.filePreviewVisible = true;
    },
    downloadFile() {
      const fullDownloadUrl = `${this.baseApi}/system/oss/file/download/${encodeURIComponent(this.previewFileName)}`;
      window.open(fullDownloadUrl, "_blank");
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    async getProjectDetail(projectId) {
      try {
        const res = await getProject(projectId);
        const data = res.data || {};
        this.whitePaperProject = {
          orgName: data.orgName || "",
          industry: data.industry || "",
          address: data.address || "",
          email: data.email || "",
          officialWebsite: data.officialWebsite || "",
          officialAccountImgUrl: this.getRelativeUrl(data.officialAccountImgUrl) || "",
          briefIntroduction: data.briefIntroduction || "",
        };
        if (data.fileList) {
          this.fileList = data.fileList.map(item => ({
            ...item,
            fileUrl: this.getRelativeUrl(item.fileUrl)
          }));
          this.showFileList = data.fileList.map(item => ({
            name: item.fileName,
            url: this.getFullUrl(item.fileUrl)
          }));
        }
      } catch (err) {
        this.$message.error("查询项目详情失败");
      }
    }
  },
};
</script>

<style scoped>
.project-form {
  width: 600px;
  margin: 0 auto;
  background-color: #ffffff !important;
  padding: 15px 0;
}

.form-container {
  width: 100%;
  background-color: #ffffff !important;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 22px;
  align-items: flex-end;
  background-color: #ffffff !important;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  background-color: #ffffff !important;
}

.form-item.full-width {
  flex: 0 0 97%;
}

.label-wrap {
  display: inline-flex;
  align-items: center;
}

.required-mark {
  color: red;
  margin-right: 4px;
  font-size: 14px;
}

.label-text {
  color: #333;
  font-size: 14px;
  line-height: 1;
}

.form-input {
  width: 100%;
  height: 36px;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

::v-deep .el-input__inner,
::v-deep .el-textarea__inner {
  background-color: #EEF4FA !important;
  border: none !important;
  box-shadow: none !important;
  height: 36px;
  border-radius: 4px;
  font-size: 14px;
}

::v-deep .el-textarea__inner {
  height: auto;
  resize: none;
}

.el-form-item__custom {
  margin-bottom: 0;
  background-color: #ffffff !important;
}

.el-form-item__error {
  color: red !important;
  font-size: 12px !important;
  margin-top: 4px !important;
  line-height: 1 !important;
  position: static !important;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #e4e7ed;
  border-radius: 4px;
  display: block !important;
  cursor: pointer;
  transition: border-color 0.3s;
  background-color: #ffffff !important;
  overflow: hidden;
  position: relative;
}

::v-deep .avatar-uploader .el-upload {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  pointer-events: auto;
}

.upload-placeholder .el-icon-plus {
  font-size: 20px;
  color: #c0c4cc;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  pointer-events: auto;
}

.file-upload .el-button:hover {
  color: #66b1ff;
  background: transparent;
}

.file-preview-content {
  padding: 20px;
  text-align: center;
}

.file-preview-content p {
  margin-bottom: 16px;
  color: #333;
  font-size: 14px;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-dialog__header {
  border-bottom: 1px solid #eee;
  padding: 15px 20px;
}

::v-deep .el-dialog__title {
  font-size: 16px;
  color: #333;
}
</style>